<template>
  <div class="page">
    <div class="showgood" v-for="(item, index) in tabledata" :key="index">
      <div class="img">
        <img :src="item.GoodImg" width="180px" height="180px" alt="" />
      </div>
      <p>{{ item.GoodName }}</p>
      <p>{{ item.GoodArea }}</p>
      <p>￥{{ item.GoodPrice }}</p>
      <p>
        <button @click="zhanshi(item.GoodId)">查看</button>
        <button @click="tocar(item.GoodId)">加入购物车</button>
      </p>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageindex"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalcount"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tabledata: {
        GoodId: "",
        GoodName: "",
        GoodPrice: "",
        GoodArea: "",
        GoodBanben: "",
        GoodColor: "",
        GoodImg: "",
        GoodCount: "",
      },
      pageindex: 1,
      pagesize: 2,
      totalcount: 0,
      Carform: {
        GoodId: "",
        UserId: "",
        CarCount: "",
      },
    };
  },
  methods: {
    getgoods() {
      this.$axios({
        url: "http://localhost:13443/api/Goods/GetGood",
        method: "get",
        params: {
          pageindex: this.pageindex,
          pagesize: this.pagesize,
        },
      }).then((res) => {
        this.tabledata = res.data.list;
        this.totalcount = res.data.totalcount;
      });
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.getgoods();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pageindex = val;
      this.getgoods();
      console.log(`当前页: ${val}`);
    },
    tocar(GoodId) {
      let userid = sessionStorage.getItem("userid");
      if (userid != null) {
        (this.Carform.GoodId = GoodId),
          (this.Carform.CarCount = 1);
        this.Carform.UserId = userid;
        this.$axios({
          url: "http://localhost:13443/api/Goods/AddShopCar",
          method: "post",
          data: this.Carform,
        }).then((res) => {
          if (res.data > 0) {
            alert("添加成功");
            this.$router.push("/ShopCar");
            return;
          }
          alert('添加失败')
        });
      } else {
        this.$router.push("/Login");
      }
    },
    zhanshi(GoodId) {
      this.$router.push("/zhanshi/" + GoodId);
    },
  },
  created() {
    this.getgoods();
  },
};
</script>

<style>
.page {
  margin: 0 auto;
  width: 1608px;
  height: 680px;
  background-color: lightgray;
}
.showgood {
  background-color: white;
  width: 400px;
  height: 340px;
  float: left;
  border: 1px solid rgb(5, 5, 5);
}
.block {
  float: left;
}
</style>